<template>
    <el-card v-loading='loading'>
        <div slot="header">
            <span>修改密码</span>
        </div>
        <el-form :rules="rules" :model="ruleForm" ref="changePwdForm">
            <el-form-item label="原密码" prop="pwd">
                <el-input placeholder="请输入原密码" type="password" v-model="ruleForm.pwd"/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPwd">
                <el-input placeholder="请输入新密码" type="password" v-model="ruleForm.newPwd"/>
            </el-form-item>
            <el-form-item label="确认新密码" prop="newPwdSure">
                <el-input placeholder="请再次输入新密码" type="password" v-model="ruleForm.newPwdSure"/>
            </el-form-item>
            <el-button type="primary" @click="changePwd">确认修改</el-button>
        </el-form>
    </el-card>
</template>

<script>
    import {changePwdReqApi} from "../api/userApi";

    export default {
        name: "ChangePwd",
        data() {
            let checkPasswordSureValidator = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入新密码'));
                } else if (value !== this.ruleForm.newPwd) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                loading: false,
                ruleForm: {
                    pwd: '',
                    newPwd: '',
                    newPwdSure: '',
                },
                rules: {
                    pwd: [{required: true, message: '请输入密码', trigger: 'blur'}],
                    newPwd: [{required: true, message: '请输入新密码', trigger: 'blur'}],
                    newPwdSure: [{validator: checkPasswordSureValidator, trigger: 'blur'}]
                }
            }
        },
        methods: {
            changePwd() {
                this.$refs['changePwdForm'].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        changePwdReqApi(this.ruleForm.pwd, this.ruleForm.newPwd).then(res => {
                            this.loading = false;
                            if (res.status === 0) {
                                this.$message.success(res.msg);
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                    }
                });
            }
        }
    }
</script>

<style scoped lang="stylus">
    .el-card {
        text-align left
        border 1px solid #ccc
        border-top 3px solid cornflowerblue
        border-radius 5px
        margin 10px
    }
</style>
